<template>
  <div class="singer">
    <load v-if="!singer.length"></load>
    <listview @select="selectSinger" :data="singer" :llist="letList" ></listview>
    <router-view></router-view>
  </div>
</template>

<script>

import listview from '../base/listview'
import Jspinyin from 'js-pinyin'
import {mapMutations} from 'vuex'
import load from '../base/load'

export default {
  components: {
    listview,
    load

  },
  data() {
    return {
      singerList: [],
      singer: [],
      params: {
        data: {
          comm: { ct: 24, cv: 0 },
          singerList: {
            module: 'Music.SingerListServer',
            method: 'get_singer_list',
            param: {
              area: -100,
              sex: -100,
              genre: -100,
              index: -100,
              sin: 0,
              cur_page: 1
            }
          }
        }
      }
    }
  },
  created() {
    this.getSingerList(this.params)
  },
  methods: {
    selectSinger(singer) {
      this.$router.push({
        path: `/singer/${singer.id}`
      })
      this.setSinger(singer)
    },
    getNorma(list) {
      let map = {
        hot: {
          title: '热门',
          items: []
        }
      }
      list.forEach((value, index) => {
        if (index < 10) {
          map.hot.items.push({
            mid: value.singer_mid,
            id: value.singer_id,
            img: value.singer_pic,
            name: value.singer_name
          })
        }
        const key = value.firstLet
        if (!map[key]) {
          map[key] = {
            title: key,
            items: []
          }
        }
        map[key].items.push({
          mid: value.singer_mid,
          id: value.singer_id,
          img: value.singer_pic,
          name: value.singer_name
        })
      })
      let hot = []
      let ret = []
      for (let key in map) {
        let val = map[key]
        if (val.title.match(/[A-Z]/)) {
          ret.push(val)
        } else if (val.title === '热门') {
          hot.push(val)
        }
      }
      ret.sort((a, b) => {
        return a.title.charCodeAt(0) - b.title.charCodeAt(0)
      })
      return hot.concat(ret)
    },
    getSingerList(param) {
      this.axios
        .get('list/cgi-bin/musicu.fcg?', {
          params: param
        })
        .then(res => {
          if (res.data.singerList.code == 0) {
            this.singerList = res.data.singerList.data.singerlist
            this.singerList.forEach((value, index) => {
              value.firstLet = Jspinyin.getFullChars(value.singer_name)[0][0]
                .charAt(0)
                .toUpperCase()
            })
            this.singer = this.getNorma(this.singerList)
          }
        })
    },
    ...mapMutations({
      setSinger: 'SET_SINGER'
    })
  },
  computed: {
    letList() {
      return this.singer.map((value) => {
        return value.title.substr(0, 1)
      })
    }
  }
}
</script>

<style lang="scss" scoped>

</style>
